package com.walixiwa.m3udownloader.utils;

import android.content.Context;


import com.walixiwa.m3udownloader.DownloadListener;
import com.walixiwa.m3udownloader.model.DownloadTaskModel;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import jaygoo.library.m3u8downloader.M3U8Downloader;
import jaygoo.library.m3u8downloader.M3U8DownloaderConfig;
import jaygoo.library.m3u8downloader.OnM3U8DownloadListener;
import jaygoo.library.m3u8downloader.bean.M3U8Task;

public class DownloadManager {
    private static DownloadListener listener;
    private static List<DownloadTaskModel> tasks = new ArrayList<>();

    public static void init(Context context) {
        TaskManager.init(context);
        DownloadManager.setTasks(TaskManager.getInstance().getTaskList());

        M3U8DownloaderConfig.build(context).setSaveDir(getSaveDir(context)).setConnTimeout(10000).setReadTimeout(10000).setThreadCount(30).setDebugMode(true);
        M3U8Downloader.getInstance().setOnM3U8DownloadListener(DownloadManager.downloadListener);
    }

    private static String getSaveDir(Context context) {
        return context.getFilesDir().getAbsolutePath() + File.separator + "M3U8" + File.separator;
    }

    public static void addTask(String title, String url) {
        DownloadTaskModel model = new DownloadTaskModel();
        model.setUrl(url);
        model.setName(title);
        model.setProgress(0);
        model.setInfo("等待下载");
        model.setSpeed("0 B/s");
        if (!TaskManager.getInstance().isExists(url)) {
            DownloadManager.getTasks().add(model);
            M3U8Downloader.getInstance().download(url);
            TaskManager.getInstance().setTask(model);
            startNext();
        }
    }

    public static void setListener(DownloadListener listener) {
        DownloadManager.listener = listener;
    }

    public static List<DownloadTaskModel> getTasks() {
        return tasks;
    }

    public static void setTasks(List<DownloadTaskModel> tasks) {
        DownloadManager.tasks = tasks;
    }

    private static OnM3U8DownloadListener downloadListener = new OnM3U8DownloadListener() {
        @Override
        public void onDownloadItem(M3U8Task task, long itemFileSize, int totalTs, int curTs) {
            super.onDownloadItem(task, itemFileSize, totalTs, curTs);
            int position = getTaskPosition(task);
            if (position != -1) {
                DownloadManager.getTasks().get(position).setInfo(curTs + " / " + totalTs);
                DownloadManager.getTasks().get(position).setSpeed(task.getFormatSpeed());
                DownloadManager.getTasks().get(position).setProgress((int) (task.getProgress() * 100));
                TaskManager.getInstance().setTask(DownloadManager.getTasks().get(position));
            }
            if (listener != null) {
                listener.onDownloadItem(task, itemFileSize, totalTs, curTs);
            }
        }

        @Override
        public void onDownloadSuccess(M3U8Task task) {
            super.onDownloadSuccess(task);
            int position = getTaskPosition(task);
            if (position != -1) {
                DownloadManager.getTasks().get(position).setInfo("下载完成");
                DownloadManager.getTasks().get(position).setSpeed(task.getFormatTotalSize());
                DownloadManager.getTasks().get(position).setProgress(100);
                TaskManager.getInstance().setTask(DownloadManager.getTasks().get(position));
            }
            if (listener != null) {
                listener.onDownloadSuccess(task);
            }
            startNext();
        }

        @Override
        public void onDownloadPause(M3U8Task task) {
            super.onDownloadPause(task);
            int position = getTaskPosition(task);
            if (position != -1) {
                DownloadManager.getTasks().get(position).setInfo("下载暂停");
                DownloadManager.getTasks().get(position).setSpeed(task.getFormatSpeed());
                DownloadManager.getTasks().get(position).setProgress((int) (task.getProgress() * 100));
                TaskManager.getInstance().setTask(DownloadManager.getTasks().get(position));
            }
            if (listener != null) {
                listener.onDownloadPause(task);
            }
        }

        @Override
        public void onDownloadPending(M3U8Task task) {
            super.onDownloadPending(task);
            int position = getTaskPosition(task);
            if (position != -1) {
                DownloadManager.getTasks().get(position).setInfo("等待下载");
                DownloadManager.getTasks().get(position).setSpeed(task.getFormatSpeed());
                DownloadManager.getTasks().get(position).setProgress(0);
                TaskManager.getInstance().setTask(DownloadManager.getTasks().get(position));
            }
            if (listener != null) {
                listener.onDownloadPending(task);
            }
        }

        @Override
        public void onDownloadProgress(M3U8Task task) {
            super.onDownloadProgress(task);
            int position = getTaskPosition(task);
            if (position != -1) {
                DownloadManager.getTasks().get(position).setSpeed(task.getFormatSpeed());
                DownloadManager.getTasks().get(position).setProgress((int) (task.getProgress() * 100));
                TaskManager.getInstance().setTask(DownloadManager.getTasks().get(position));
            }
            if (listener != null) {
                listener.onDownloadProgress(task);
            }
        }

        @Override
        public void onDownloadPrepare(M3U8Task task) {
            super.onDownloadPrepare(task);
            int position = getTaskPosition(task);
            if (position != -1) {
                DownloadManager.getTasks().get(position).setInfo("开始准备下载...");
                DownloadManager.getTasks().get(position).setSpeed(task.getFormatSpeed());
                DownloadManager.getTasks().get(position).setProgress(0);
                TaskManager.getInstance().setTask(DownloadManager.getTasks().get(position));
            }
            if (listener != null) {
                listener.onDownloadPrepare(task);
            }
        }

        @Override
        public void onDownloadError(M3U8Task task, Throwable errorMsg) {
            super.onDownloadError(task, errorMsg);
            int position = getTaskPosition(task);
            if (position != -1) {
                DownloadManager.getTasks().get(position).setInfo("下载错误:" + errorMsg.toString());
                DownloadManager.getTasks().get(position).setSpeed(task.getFormatSpeed());
                DownloadManager.getTasks().get(position).setProgress((int) (task.getProgress() * 100));
                TaskManager.getInstance().setTask(DownloadManager.getTasks().get(position));
            }
            if (listener != null) {
                listener.onDownloadError(task, errorMsg);
            }
            startNext();
        }
    };

    public static void startNext() {
        for (int i = 0; i < DownloadManager.getTasks().size(); i++) {
            if (!M3U8Downloader.getInstance().checkM3U8IsExist(DownloadManager.getTasks().get(i).getUrl())) {
                if (!M3U8Downloader.getInstance().isRunning()) {
                    M3U8Downloader.getInstance().download(DownloadManager.getTasks().get(i).getUrl());
                }
            }
        }
    }

    private static int getTaskPosition(M3U8Task task) {
        for (int i = 0; i < tasks.size(); i++) {
            if (tasks.get(i).getUrl().equals(task.getUrl())) {
                return i;
            }
        }
        return -1;
    }
}
